const { toTryCatch, flatArrayObject } = require("../../utils")
const fileIO = require("../../utils/fileIO");
const fs = require('fs-extra');

const fileDao = {
    getFileTreeDao: async (req, data) => {
        const hVideo = await req.Model.find(data);

        // 如果数据库中不存在hVideo文件夹
        // 获取第一个可读写的磁盘
        const diskRWName = await fileIO.getFirstReadableWritableDrive();
        if (diskRWName) {
            // 默认是其他磁盘
            let hVideoFolderPath = `${diskRWName}/hVideo`;
            // 如果是C盘
            if (diskRWName.includes('C')) {
                hVideoFolderPath = `C:/Users/${require('os').userInfo().username}/hVideo`;
            }
            // 是否存在hVideo文件夹
            const isExist = await fileIO.checkDirectoryExistenceAndAccess(hVideoFolderPath);
            if (!isExist) {
                // 创建hVideo文件夹
                await fileIO.createDirectory(hVideoFolderPath);
            }
            // 生成文件树
            const fileTree = await fileIO.generateFileTree(hVideoFolderPath);
            // 扁平化文件树
            const flatFileTree = flatArrayObject(JSON.parse(JSON.stringify(fileTree.children)), 'children', true);
            // 将hVideo文件夹信息添加到文件树中
            flatFileTree.unshift({
                name: 'hVideo',
                type: 'root',
                path: hVideoFolderPath,
            })
            // 将不存在的文件夹信息添加到数据库中，存在的进行更新
            const bulkOps = flatFileTree.map((file) => {
                if(file.type === 'file') {
                    // 使用fs获取文件大小
                    file.size = fs.statSync(file.path).size;
                }
                return {
                    updateOne: {
                        filter: { path: file.path },
                        update: { $set: file },
                        upsert: true
                    }
                }
            })
            await req.Model.bulkWrite(bulkOps);
            return fileTree;
        } else {
            return { type: 'error', message: '没有可读写的磁盘！' }
        }
    },
    getVideoFileDao: async (req, id) => {
        const res = await req.Model.find({ id }).populate("children");
        return res;
    }
}
module.exports = fileDao;